/**
 * This script was used for BP to get coordinates from the Google Maps API.
 * There's a 1 second interval between requests so that the API won't block us.
 *
 * The coords from here need to be manually copied to mapCoords.js which is used
 * as the coordinates bank by googlemapScript.js, which is the final script which
 * the user (BP in the original case) puts in his pivot.
 *
 * The coordinates are stored in the 'geoMappings' object.
 * The details of the addresses that the API didn't find are stored in the 'failedMappings' object.
 */


/*
 * set to true when replacing widget rendering engine.
 */
this.isCustom = true;

/*
 * exectuted after the widget was first initialized, useful when overriding entire widget rendering, i/e replacing the button with a whole different button ux
 * @param {args} wraps all function arguments, including widget, dashboard and widget controller instances.
 */
this.init = function (args) {


};

/*
 * executed before the widget query result is loaded to the DOM and allows canceling such beavior and replace it with custom widget implementation.
 * to cancel the default population just set 'args.cancel = true' and the widget default population will be ignored.
 * @param {args} wraps all function arguments, including query result, widget, dashboard and widget controller instances.
 */
this.beforeResultLoaded = function (args) {


};

/*
 * executed after the widget result were added to the DOM. useful to apply DOM tweaks after query result population.
 * @param {args} wraps all function arguments, including query result, widget, dashboard and widget controller instances.
 */
this.afterResultLoaded = function (args) {

    var colCountry = 0,
        colCity = 1,
        colAddress = 2,
        colSupplier = 3;

    var rowscount = args.result.data.length,
        cData = args.result.data,
        me = this;

    $.getScript('https://maps.googleapis.com/maps/api/js?key=AIzaSyATEZa2VBWm5kEj4Y97fFXT5g4Zf0pG--s&sensor=false', function(data, textStatus) {
    $.getScript('https://maps.gstatic.com/intl/en_us/mapfiles/api-3/8/4/main.js', function(data, textStatus) {

        var geocoder = new google.maps.Geocoder();
        var geoMappings = {},
            failedMappings = {},
            rowHandledCount = 0;

        var containerId = $(args.element).attr('id');
        var container = $('#' + containerId);

        var getAddress = function (row) {

            return row[colAddress] + ', ' + row[colCity] + ', ' + row[colCountry];
        };


        var latlng = new google.maps.LatLng(0,0);
        var myOptions = {
          zoom: 3,
          center: latlng,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(args.element, myOptions);

        var targetWidget = args.widget.dashboard.getWidget('P5d7f3ea42412452a9227139c31379f');
        var onMarkerClicked = function (marker) {

            prism.WidgetClient.sendAction(targetWidget, {
                action: DashboardActionHandler.WidgetSelectionHandler,
                SelectedMembers: encodeURIComponent(JSON.stringify(marker.id))
            })
        };

        var rowCounter = 0;

        var int = window.setInterval("codeAddress()", 1000);
        codeAddress = function () {

            debugger
            if (rowCounter == rowscount) return finished();
            rowCounter++;
            var row = args.result.getRow(rowCounter);
            if (row) {

                rowHandledCount++;
                var address = getAddress(row),
                    id = row[colSupplier];

                geocoder.geocode( { 'address': address }, function(results, status) {

                    if (status == google.maps.GeocoderStatus.OK) {

                        geoMappings[id] = results[0].geometry.location;

                        var marker = new google.maps.Marker({
                          map: map,
                          position: results[0].geometry.location,
                          id: id,
                          address: address
                        });
                        google.maps.event.addListener(marker, 'click', function() { onMarkerClicked(marker) });

                    } else {
                        failedMappings[id] = { address: address, status: status };
                    }

                    //rowCounter++;
                    //return codeAddress(rowCounter);
                    //return setTimeout(me.codeAddress(), 1000);
                });
            }
        };

        //codeAddress(0);

        var finished = function () {

            window.clearInterval(int);
            debugger
            return true;
        };

    });
    });
};

/*
 * exectuted after all dashboard widget models were initialized. useful for binding with other widget events.
 * @param {args} wraps all function arguments, including widget, dashboard and widget controller instances.
 */
this.handleDashboardInitialized = function (args) {
};
